package com.tozny.aes_crypto_sample.slice;

import com.tozny.aes_crypto_sample.ResourceTable;
import com.tozny.crypto.openohos.AesCbcWithIntegrity;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;

/**
 * MainAbilitySlice
 *
 * @since 2021-03-19
 */
public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");
    private static final boolean ISPASSWORD_BASED_KEY = true;
    private static final String EXAMPLE_P = "always use passphrases for passwords wherever possible!";
    private static final String TAG = "Tozny";

    AesCbcWithIntegrity.CipherTextIvMac civ = null;
    ToastDialog toastDialog;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        String textToEncrypt = "Testing shows the presence, not the absence of bugs.Edsger W. Dijkstra";
        String keyStr = getSecretKeys(ISPASSWORD_BASED_KEY, EXAMPLE_P);

        TextField initialData = (TextField) findComponentById(ResourceTable.Id_initialData);
        Text encryptText = (Text) findComponentById(ResourceTable.Id_encryptText);
        Text decryptedText = (Text) findComponentById(ResourceTable.Id_decryptedText);
        initialData.setText(textToEncrypt);

        Button encryptbutton = (Button) findComponentById(ResourceTable.Id_Encryptbutton);
        Button decryptedbutton = (Button) findComponentById(ResourceTable.Id_decryptedbutton);

        encryptbutton.setClickedListener(component -> {
            if (!initialData.getText().isEmpty()) {
                try {
                    AesCbcWithIntegrity.SecretKeys secretKeys = AesCbcWithIntegrity.keys(keyStr);
                    civ = AesCbcWithIntegrity.encrypt(initialData.getText(), secretKeys, getContext());
                    HiLog.info(LABEL, "" + civ.toString());
                    encryptText.setText(civ.toString());
                } catch (InvalidKeyException invalidKeyException) {
                    HiLog.info(LABEL, "" + invalidKeyException.toString());
                } catch (GeneralSecurityException ignored) {
                    HiLog.info(LABEL, "" + ignored.toString());
                } catch (UnsupportedEncodingException unsupportedEncodingException) {
                    HiLog.info(LABEL, "" + unsupportedEncodingException.toString());
                }
            } else {
                showToast("请输入需要加密的数据！");
            }
        });

        decryptedbutton.setClickedListener(component -> {
            if (!encryptText.getText().isEmpty()) {
                try {
                    String decryptedstr = AesCbcWithIntegrity.decryptString(civ, AesCbcWithIntegrity.keys(keyStr));
                    decryptedText.setText(decryptedstr);
                } catch (InvalidKeyException invalidKeyException) {
                    HiLog.info(LABEL, "" + invalidKeyException.toString());
                } catch (GeneralSecurityException generalSecurityException) {
                    HiLog.info(LABEL, "" + generalSecurityException.toString());
                } catch (UnsupportedEncodingException unsupportedEncodingException) {
                    HiLog.info(LABEL, "" + unsupportedEncodingException.toString());
                }
            } else {
                showToast("加密后的数据不能为空！");
            }
        });
    }

    private void showToast(String msg) {
        if (toastDialog == null) {
            toastDialog = new ToastDialog(getContext());
        }
        toastDialog.setText(msg).setAlignment(LayoutAlignment.BOTTOM).show();
    }

    private String getSecretKeys(boolean isPasswordBasedkey, String examplePassword) {
        AesCbcWithIntegrity.SecretKeys key = null;
        try {
            if (ISPASSWORD_BASED_KEY) {
                // example for password based key
                String saltStr = AesCbcWithIntegrity.saltString(AesCbcWithIntegrity.generateSalt());
                key = AesCbcWithIntegrity.generateKeyFromPassword(EXAMPLE_P, saltStr);
                HiLog.info(LABEL, "key: " + key);
            } else {
                key = AesCbcWithIntegrity.generateKey();
            }
        } catch (GeneralSecurityException generalSecurityException) {
            HiLog.info(LABEL, "" + generalSecurityException.toString());
        }

        return key == null ? "" : AesCbcWithIntegrity.keyString(key);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
